package com.globallogic.socialnetwork.jsf.bean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.ServletContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.springframework.context.annotation.Scope;

import com.globallogic.socialnetwork.service.UserService;
import com.globallogic.socialnetwork.util.Constants;
import com.globallogic.socialnetwork.util.WebApplication;

/**
 * JSF Bean to handle functions associated with user's personal page
 */
@Named("personalPageBean")
@Scope("session")
public class PersonalPageBean implements Constants {

	@EJB(mappedName = "java:module/UserService")
	private UserService userService;
	private UploadedFile uploadedFile;
	private String userLogin;
	private String avatarPath;
	private final static Logger log = Logger
			.getLogger("SocialNetworkFileLogger");

	public PersonalPageBean() {
		userLogin = WebApplication.getSessionAttribute("userlogin").toString();
		avatarPath = getAvatar();
	}

	/**
	 * 
	 * @return avatar's path
	 */
	protected String getAvatar() {
		return checkAvatar().replaceFirst("/webapps", "");
	}

	/**
	 * Checks if avatar's path does exist
	 * 
	 * @return avatar's path if exists or null if doesn't
	 */
	protected String checkAvatar() {
		for (int i = 0; i < extensions.length; i++) {
			String avatarPath = dirWebImgAvatars + userLogin
					+ extensions[i].toString();
			if (new File(appPhysicalAddress+avatarPath).exists())
				return avatarPath;
		}
		return defaultAvatar;
	}

	/**
	 * Uploads selected image to web application and changes avatar's path
	 */
	public String submit() {
		File file = null;
		OutputStream output = null;

		if (uploadedFile != null)
			try {
				file = saveAvatar(uploadedFile);
				output = new FileOutputStream(file);
				IOUtils.copy(uploadedFile.getInputStream(), output);
				avatarPath = "img/avatars/" + file.getName();

			} catch (IOException e) {
				if (file != null)
					file.delete();
				WebApplication.addMessage("File upload failed with I/O error.");
			} finally {
				IOUtils.closeQuietly(output);
			}
		else
			WebApplication.addMessage("No file was chosen!");
		return "home";
	}

	/**
	 * Saves file <uploaded file> to web application
	 */
	protected File saveAvatar(UploadedFile uploadedFile) {
		OutputStream output = null;
		String extension = FilenameUtils.getExtension(uploadedFile.getName());
		File file = new File(appPhysicalAddress +dirWebImgAvatars + userLogin + "." + extension);
		deleteOldAvatar();
		
		try {
			output = new FileOutputStream(file);
			IOUtils.copy(uploadedFile.getInputStream(), output);
			return file;
		} catch (FileNotFoundException e) {
			log.error(e);
			return null;
		} catch (IOException e) {
			log.error(e);
			return null;
		}
	}

	/**
	 * Deletes old avatar
	 */
	protected void deleteOldAvatar() {
		File file = null;
		for (int i = 0; i < extensions.length; i++) {
			file = new File(appPhysicalAddress+dirWebImgAvatars + userLogin + extensions[i]);
			if (file.exists())
				file.delete();
		}
	}

	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getUserLogin() {
		return userLogin;
	}

	public void setUserLogin(String userLogin) {
		this.userLogin = userLogin;
	}

	/*
	 * public User getUser() { return user; }
	 * 
	 * public void setUser(User user) { this.user = user; }
	 */
	public String getAvatarPath() {
		avatarPath = getAvatar();
		return avatarPath;
	}

	public void setAvatarPath(String avatarPath) {
		this.avatarPath = avatarPath;
	}

}